package fr.toto.settings;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.InvalidPropertiesFormatException;
import java.util.concurrent.Phaser;

import fr.toto.constantes.Constantes;
import fr.toto.exceptions.ProcessException;
import fr.toto.logging.Login;

public final class Settings implements Constantes {

	private static String login;
	private static String token;

	public static boolean LoadSettings() {

		try {
		if (!(Files.exists(SETTINGSPATH))) {

			Files.createDirectories(SETTINGSPATH.getParent());

			if (connect()) {
				loadDefault();
				editProperties();
			} else
				return false;
		} else {
			InputStream in = Files.newInputStream(SETTINGSPATH,
					StandardOpenOption.READ);
			settings.loadFromXML(in);
		}
		} catch(IOException e) {
			
		}
		return true;
	}

	private static void loadDefault() throws InvalidPropertiesFormatException,
			IOException {
		InputStream in = Settings.class
				.getResourceAsStream("/fr/toto/settings/settings.xml");

		settings.loadFromXML(in);

		settings.setLogin(login);
		settings.setToken(token);

	}

	public static void editProperties() {

		final Phaser phaser = new Phaser();
		phaser.register();

		new SettingsUI(phaser);

		phaser.arriveAndAwaitAdvance();

	}

	private static boolean connect() {
		Phaser phaser = new Phaser();
		phaser.register();
		Login log = new Login(phaser);

		phaser.arriveAndAwaitAdvance();

		login = log.getUserName();
		token = log.getToken();

		return !log.failed();
	}

	public static void reConnect() {
		if (connect())
			try {
				
				settings.setLogin(login);
				settings.setToken(token);

				OutputStream out = Files.newOutputStream(SETTINGSPATH,
						StandardOpenOption.TRUNCATE_EXISTING);
				settings.storeToXML(out);

			} catch (Exception e) {
				new ProcessException(e);
			}
		else
			System.exit(0);
	}
}
